<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Admin\Controller;

use User\Api\UserApi;

/**
 * 后台用户控制器
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
class UserController extends AdminController
{

    /**
     * 用户管理首页
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function index()
    {

        $timestart = I('timestart');
        $timeend = I('timeend');
        //$timeend = I('timeend').' 23:59:59';
        /*$timestart = '2017-11-7 00:00:00';
        $timeend = '2017-11-8 11:52:59';*/
        //转换时间戳
        //$nickname = strtotime($nickname);
        /*$map['status'] = array('egt', 0);*/
        /*if (is_numeric($nickname)) {
            $map['uid|add_time'] = array(intval($nickname), array('like', '%'), '_multi' => true);
        } else {
            $map['add_time'] = array('like', (string)$nickname.'%' );
        }*/

        //查询数据表中被访问的链接
        $access_addr_list=M("MemberMessaged")->field("distinct visit_url")->select();
        $access_addr_array=array();
        if($access_addr_list){
            foreach($access_addr_list as $list){
                if($list['visit_url']){ array_push($access_addr_array,$list['visit_url']); }
            }
        }
        $access_addr_array=array_filter($access_addr_array);
        $this->assign("access_addr_list",$access_addr_array);
        if(isset($_GET['access_addr_search']) && $_GET['access_addr_search']){
            $map['visit_url']=addslashes($_GET['access_addr_search']);
            $this->assign("_access_addr",$_GET['access_addr_search']);
        }


        if(!empty($timestart) && !empty($timeend)){
            $map['add_time'] = array('between',array($timestart, $timeend));
        }
        $map['web_state'] = '1';

        //按日期查询数据的id
        $data = M('MemberMessaged')->where($map)->field('uid')->group("name,email,phone_number,visit_url")->select();
        $time_uid = '';
        foreach ($data as $k => $v) {
            $time_uid .= $v['uid'] . ',';
        }
        $time_uid = trim($time_uid,',');

        $list = $this->lists('MemberMessaged', $map,'',array('status'=>array('egt',0)),true,"name,email,phone_number,visit_url");
        int_to_string($list);
        foreach ($list as $k => $v) {
            $list[$k]['state'] = $v['state'] == 0 ? '未导出' : '已导出';
        }
        $this->assign('_list', $list);
        $this->assign('time_uid', $time_uid);
        $this->meta_title = '用户信息';
        $this->display();
    }

    /*
     * 推广统计
     * */
    public function hit()
    {
        $nickname = I('nickname');
        //转换时间戳
        //$nickname = strtotime($nickname);
        /*$map['status'] = array('egt', 0);*/
        if (is_numeric($nickname)) {
            $map['uid|add_time'] = array(intval($nickname), array('like', '%'), '_multi' => true);
        } else {
            $map['add_time'] = array('like', (string)$nickname . '%');
        }
        $map['web_state'] = '2';
        $list = $this->lists_data('MemberMessaged', $map);

        int_to_string($list);


        //组装数组
        $arr = array();
        foreach ($list as $k => $v) {
            $arr[] = $v[visit_url];

        }

        //去重数组
        $arr = array_unique($arr);

        //空的都值去掉
        foreach( $arr as $k=>$v){
            if( !$v )
                unset( $arr[$k] );
        }

        //统计数组
        $count = array_count_values(array_column($list, "visit_url"));

        //进行数组的组装，多个数据一样的，只显示一条，并且统计个数
        $listCount = [];

        foreach ($arr as $k => $v) {

            $hit = isset($count[$v]) ? $count[$v] : 0;
           $data= $this->wipehit($v,$arr);
            if($data==true){
                $listCount[] = [
                    'visit_url' => $v,
                    'hit' => $hit,
                ];
            }

        }


        /*//组装数据
        $checkMap = array();
        $newData = array();
        foreach ($list as $k=>$v) {
            $a = array_count_values($v['visit_url']);
            if (!in_array($v['visit_url'], $checkMap)) {
                $v['state'] = $v['state'] == 0 ? '未导出' : '已导出';
                $checkMap[] = $v['visit_url'];
                $newData[] = $v;
            }
        }*/

        $this->assign('_list', $listCount);
        $this->meta_title = '用户信息';
        $this->display("hit");
    }
    /**
     * 去除1,3,5页面
     * @author huajie <banhuajie@163.com>
     */
    public function wipehit($v,$arr)
    {
    $arr=count($arr);
        $aa=explode('/',$v);
        for($i=1;$i<=$arr+1;$i++){
            $i++;
            if($aa['6']=='generalize_'.$i){
                return true;
            }
        }
    }


    /**
     * 修改昵称初始化
     * @author huajie <banhuajie@163.com>
     */
    public function updateNickname()
    {
        $nickname = M('Member')->getFieldByUid(UID, 'nickname');
        $this->assign('nickname', $nickname);
        $this->meta_title = '修改昵称';
        $this->display();
    }

    /**
     * 修改昵称提交
     * @author huajie <banhuajie@163.com>
     */
    public function submitNickname()
    {
        //获取参数
        $nickname = I('post.nickname');
        $password = I('post.password');
        empty($nickname) && $this->error('请输入昵称');
        empty($password) && $this->error('请输入密码');

        //密码验证
        $User = new UserApi();
        $uid = $User->login(UID, $password, 4);
        ($uid == -2) && $this->error('密码不正确');

        $Member = D('Member');
        $data = $Member->create(array('nickname' => $nickname));
        if (!$data) {
            $this->error($Member->getError());
        }

        $res = $Member->where(array('uid' => $uid))->save($data);

        if ($res) {
            $user = session('user_auth');
            $user['username'] = $data['nickname'];
            session('user_auth', $user);
            session('user_auth_sign', data_auth_sign($user));
            $this->success('修改昵称成功！');
        } else {
            $this->error('修改昵称失败！');
        }
    }

    /**
     * 修改密码初始化
     * @author huajie <banhuajie@163.com>
     */
    public function updatePassword()
    {
        $this->meta_title = '修改密码';
        $this->display();
    }

    /**
     * 修改密码提交
     * @author huajie <banhuajie@163.com>
     */
    public function submitPassword()
    {
        //获取参数
        $password = I('post.old');
        empty($password) && $this->error('请输入原密码');
        $data['password'] = I('post.password');
        empty($data['password']) && $this->error('请输入新密码');
        $repassword = I('post.repassword');
        empty($repassword) && $this->error('请输入确认密码');

        if ($data['password'] !== $repassword) {
            $this->error('您输入的新密码与确认密码不一致');
        }

        $Api = new UserApi();
        $res = $Api->updateInfo(UID, $password, $data);
        if ($res['status']) {
            $this->success('修改密码成功！');
        } else {
            $this->error($res['info']);
        }
    }

    /**
     * 用户行为列表
     * @author huajie <banhuajie@163.com>
     */
    public function action()
    {
        //获取列表数据
        $Action = M('Action')->where(array('status' => array('gt', -1)));
        $list = $this->lists($Action);
        int_to_string($list);
        // 记录当前列表页的cookie-
        Cookie('__forward__', $_SERVER['REQUEST_URI']);

        $this->assign('_list', $list);
        $this->meta_title = '用户行为';
        $this->display();
    }

    /**
     * 新增行为
     * @author huajie <banhuajie@163.com>
     */
    public function addAction()
    {
        $this->meta_title = '新增行为';
        $this->assign('data', null);
        $this->display('editaction');
    }

    /**
     * 编辑行为
     * @author huajie <banhuajie@163.com>
     */
    public function editAction()
    {
        $id = I('get.id');
        empty($id) && $this->error('参数不能为空！');
        $data = M('Action')->field(true)->find($id);

        $this->assign('data', $data);
        $this->meta_title = '编辑行为';
        $this->display();
    }

    /**
     * 更新行为
     * @author huajie <banhuajie@163.com>
     */
    public function saveAction()
    {
        $res = D('Action')->update();
        if (!$res) {
            $this->error(D('Action')->getError());
        } else {
            $this->success($res['id'] ? '更新成功！' : '新增成功！', Cookie('__forward__'));
        }
    }

    /**
     * 会员状态修改
     * @author 朱亚杰 <zhuyajie@topthink.net>
     */
    public function changeStatus($method = null)
    {

        $id = array_unique((array)I('id', 0));
        if (in_array(C('USER_ADMINISTRATOR'), $id)) {
            $this->error("不允许对超级管理员执行该操作!");
        }
        $id = is_array($id) ? implode(',', $id) : $id;
        if (empty($id)) {
            $this->error('请选择要操作的数据!');
        }
        $map['uid'] = array('in', $id);
        switch (strtolower($method)) {
            case 'forbiduser':
                $this->forbid('Member', $map);
                break;
            case 'resumeuser':
                $this->resume('Member', $map);
                break;
            case 'deleteuser':
                $this->delete('Member', $map);
                break;
            default:
                $this->error('参数非法');
        }
    }

    public function add($username = '', $password = '', $repassword = '', $email = '')
    {
        if (IS_POST) {
            /* 检测密码 */
            if ($password != $repassword) {
                $this->error('密码和重复密码不一致！');
            }

            /* 调用注册接口注册用户 */
            $User = new UserApi;
            $uid = $User->register($username, $password, $email);
            if (0 < $uid) { //注册成功
                $user = array('uid' => $uid, 'nickname' => $username, 'status' => 1);
                if (!M('Member')->add($user)) {
                    $this->error('用户添加失败！');
                } else {
                    $this->success('用户添加成功！', U('index'));
                }
            } else { //注册失败，显示错误信息
                $this->error($this->showRegError($uid));
            }
        } else {
            $this->meta_title = '新增用户';
            $this->display();
        }
    }

    /**
     * 获取用户注册错误信息
     * @param  integer $code 错误编码
     * @return string        错误信息
     */
    private function showRegError($code = 0)
    {
        switch ($code) {
            case -1:
                $error = '用户名长度必须在16个字符以内！';
                break;
            case -2:
                $error = '用户名被禁止注册！';
                break;
            case -3:
                $error = '用户名被占用！';
                break;
            case -4:
                $error = '密码长度必须在6-30个字符之间！';
                break;
            case -5:
                $error = '邮箱格式不正确！';
                break;
            case -6:
                $error = '邮箱长度必须在1-32个字符之间！';
                break;
            case -7:
                $error = '邮箱被禁止注册！';
                break;
            case -8:
                $error = '邮箱被占用！';
                break;
            case -9:
                $error = '手机格式不正确！';
                break;
            case -10:
                $error = '手机被禁止注册！';
                break;
            case -11:
                $error = '手机号被占用！';
                break;
            default:
                $error = '未知错误';
        }
        return $error;
    }


    /**
     * 会员删除
     */
    public function deleteMember($method = null)
    {
        $id = array_unique((array)I('id', 0));
        if (in_array(C('USER_ADMINISTRATOR'), $id)) {
            $this->error("不允许对超级管理员执行该操作!");
        }
        $id = is_array($id) ? implode(',', $id) : $id;
        if (empty($id)) {
            $this->error('请选择要操作的数据!');
        }
        $map['uid'] = array('in', $id);
        $msg = array('success' => '删除成功！', 'error' => '删除失败！');
        $msg = array_merge(array('success' => '操作成功！', 'error' => '操作失败！', 'url' => '', 'ajax' => IS_AJAX), (array)$msg);
        if (M('member_messaged')->where($map)->delete() !== false) {
            $this->success($msg['success'], $msg['url'], $msg['ajax']);
        } else {
            $this->error($msg['error'], $msg['url'], $msg['ajax']);
        }
    }


    /*
     * 导出员工信息
     */
    public function pullInfo()
    {
        $search_condition="";
        if(isset($_POST['import_condition']) && $_POST['import_condition']){
            $condition=json_decode($_POST['import_condition'],1);
            if(isset($condition['condition']) && $condition['condition']){
                $access_url=$condition['condition']['access_url'];
                $time_search=$condition['condition']['time_search'];
                $condition_str="";
                if($access_url){
                    $condition_str.=" and visit_url=".addslashes($access_url);
                }
                if(isset($time_search['inpend']) && $time_search['inpend']){
                    $condition_str.=" and add_time>'".$time_search['inpstart']."' and add_time<='".$time_search['inpend']."'";
                }
                $search_condition="web_state=1 ".$condition_str;
                $data=M("member_messaged")->field('uid,name,email,phone_number,visit_url,visit_ip,add_time')->where($search_condition)->group("name,email,phone_number,visit_url")->order("uid desc")->limit(10000)->select();
            }else if(isset($condition['list']) && $condition['list']){
                $need_import_list=$condition['list'];
                $search_condition="uid in (".implode(",",$need_import_list).") and web_state=1";
                $data=M("member_messaged")->field('uid,name,email,phone_number,visit_url,visit_ip,add_time')->where($search_condition)->group("name,email,phone_number,visit_url")->order("uid desc")->select();
            }else{
                exit(0);
            }
        }


        //2017-11-8  修改按时间区间来导出表格
        /*$id = array_unique((array)I('id', 0));
        if (in_array(C('USER_ADMINISTRATOR'), $id)) {
            $this->error("不允许对超级管理员执行该操作!");
        }
        $id = is_array($id) ? implode(',', $id) : $id;
        if (empty($id)) {
            $this->error('请选择要操作的数据!');
        }
        $map['uid'] = array('in', $id);*/
        //$map['state'] = 0;

        $rowtitle = array('序列号', '姓名', '邮箱', '电话号码', '访问网址', '访问IP', '访问时间');
        $rowval = array('A' => 'uid', 'B' => 'name', 'C' => 'email', 'D' => 'phone_number', 'E' => 'visit_url', 'F' => 'visit_ip', 'G' => 'add_time');
        $setwidth = array('A' => '20', 'B' => '20', 'C' => '20', 'D' => '20', 'E' => '60', 'F' => '20', 'G' => '20');
        //修改导出数据的状态
        $re = M('member_messaged')->where($search_condition)->save(array('state' => 1));
        /*foreach ($data as $k => $v) {
            $data[$k]['add_time'] = date('Y-m-d', $v['add_time']);
        }*/
        pullExcel($data, $rowtitle, $rowval, $setwidth, '推广的用户信息');
    }


    /**
     * 用户管理首页
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function ajax_time()
    {
        //开始时间
        $timestart = I('timestart') ;
        $timestart ='2017-11-05' ;

        //结束时间
        $timeend = I('timestart');
        $timeend ='2017-11-07 23:59:59' ;

        $map['add_time'] = array('between',array($timestart, $timeend));

        $map['web_state'] = '1';
        $list = $this->lists('MemberMessaged', $map);
        int_to_string($list);
        foreach ($list as $k => $v) {
            $list[$k]['state'] = $v['state'] == 0 ? '未导出' : '已导出';
        }

        apiSuccess($list);
    }


}
